package com.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.health.excel.OrderSettingListener;
import com.health.pojo.OrderSetting;
import com.health.service.OrderSettingService;
import com.health.vo.Result;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orderSetting")
@PreAuthorize("hasRole('ROLE_ADMIN')") //拥有ROLE_ADMIN角色才可以访问当前Controller下的方法
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    /**
     * 设置可预约人数
     */
    @PostMapping("/editNumber")
    public Result editNumber(@RequestBody OrderSetting orderSetting) {
        orderSettingService.editNumber(orderSetting);

        return new Result(true, "设置成功");
    }

    /**
     * 根据年月查询预约设置
     */
    @GetMapping("/findByDate")
    public Result findByDate(@DateTimeFormat(pattern = "yyyy-MM") Date date) {
        List<Map<String, Integer>>settingList = orderSettingService.findByDate(date);

        return new Result(true, "查询预约设置成功", settingList);
    }

    /**
     * 上传预约设置Excel
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) throws IOException {
        //读取Excel文件
        EasyExcel.read(
                excelFile.getInputStream(),
                OrderSetting.class,
                new OrderSettingListener(orderSettingService)
        ).sheet().doRead();

        return new Result(true, "预约设置上传成功");
    }

    /**
     * 校验体检日期
     */
    @GetMapping("/checkOrderDate")
    public Result checkOrderDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date orderDate) {
        OrderSetting orderSetting = orderSettingService.findByOrderDate(orderDate);
        if (orderSetting == null) {
            //未设置预约
            System.out.println("111");
            return new Result(false, "所选日期无法预约");
        } else if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //已设置，但是预约已满
            System.out.println("222");
            return new Result(false, "所选日期预约已满");
        }

        System.out.println("333");
        return new Result(true, "所选日期可以预约");
    }
}
